from flask import abort, jsonify
from flask import render_template, current_app, g
from flask import request

from info.modules.utils.common import user_login_data

from info import constants, db
from info.models import News
from info.modules.utils.response_code import RET
from . import news_blu


@news_blu.route("/<int:news_id>")
@user_login_data
def news_detail(news_id):
    # 右侧新闻点击排行
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    range_news_list = []
    # 如果news_list是空,返回None,不报错=>news_list is not iterator
    # ???????????????????????????????????????????疑问
    for news in news_list if news_list else None:
        # news 是一个User的对象,即模板对象,自定义函数to_basic_dict()
        range_news_list.append(news.to_basic_dict())


    # 详情页新闻数据展示
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        abort(404)

    if not news:
        abort(404)

    # 回头验证点击次数怎么是加1此
    news.clicks +=1
    # 组装数据


    # 根据数据库显示新闻是否被收藏
    is_collected = False
    if g.user:
        collection_news = g.user.collection_news
        if news in collection_news:
            is_collected = True


    data = {
        # 如果g.user是空, 就将None赋值给user_info
        "user_info": g.user.to_dict() if g.user else None,
        "range_news_list": range_news_list,
        "news": news,
        "is_collected": is_collected
    }
    return render_template("news/detail.html", data=data)


@news_blu.route("/news_collect", methods=["POST"])
@user_login_data
def news_collect():
    # 1. 接收函数
    user = g.user
    json_data = request.json
    news_id = json_data.get("news_id")
    action = json_data.get("action")
    current_app.logger.debug(news_id)

    # 2. 校验函数
    if not user:
        return jsonify(errno=RET.PARAMERR, errmsg="用户未登录")

    if not news_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误1")

    if action not in ("collect", "cancel_collect"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误2")

    # 3. 查询新闻
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻查询错误")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="该新闻不存在")

    # 4. 操作数据
    if action == "collect":
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="错作失败")

    return jsonify(errno=RET.OK, errmsg="操作成功")